package com.example.demo.controller;

import java.text.DateFormat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.SaleKeHuGuanXi;
import com.example.demo.entity.SaleKeHuGuanXi2;
import com.example.demo.form.BackMonkeyForm2;
import com.example.demo.form.SaleKeHuGuanXi2Form;
import com.example.demo.service.SaleKeHuGuanXi2Service;
import com.example.demo.service.SaleKeHuGuanXiService;
import com.sun.el.parser.ParseException;

@RestController
@RequestMapping(value = "/SaleKeHuGuanXi2")
public class SaleKeHuGuanXi2Controller {
	@Autowired
	private SaleKeHuGuanXiService service1;
	@Autowired
	private SaleKeHuGuanXi2Service service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(value = "/save")
	private Object save(SaleKeHuGuanXi2Form Form) throws java.text.ParseException {
		Integer saleId1 = Form.getId();
		Date d= new Date();
		Date d1 = dateFormat1.parse("1999-01-01");
		SaleKeHuGuanXi sale1= new SaleKeHuGuanXi();
		SaleKeHuGuanXi Sale1= new SaleKeHuGuanXi();
		SaleKeHuGuanXi2 sale2= new SaleKeHuGuanXi2();
		SaleKeHuGuanXi2 Sale2= new SaleKeHuGuanXi2();
		if(saleId1==null) {
			Sale1.setMonth(Form.getMonth());
			Sale1.setYears(Form.getYears());
			sale1 = service1.save(Sale1);
		}else {
			 sale1 = service1.findById(saleId1);
			 sale1.setMonth(Form.getMonth());
			 sale1.setYears(Form.getYears());
			 service1.save(sale1);
				List<SaleKeHuGuanXi2> list = service2.findBySalekehuguanxi(sale1);
				for (SaleKeHuGuanXi2 SaleKeHuGuanXi2 : list) {
					if(d1.compareTo(SaleKeHuGuanXi2.getBeginDate())==-1) {
						d1=SaleKeHuGuanXi2.getBeginDate();
						Sale2=SaleKeHuGuanXi2;
					}
				}
				Sale2.setEndDate(d);
				service2.save(Sale2);
				
		}
		BeanUtils.copyProperties(Form, sale2, "id");
		sale2.setSalekehuguanxi(sale1);
		sale2.setBeginDate(d);
		service2.save(sale2);
		return new AjaxResult("数据保存成功");			
	}
	
	@RequestMapping(value = "/findbydate")
	public Object findbyId() throws ParseException, java.text.ParseException {
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d = dateFormat1.parse("1999-01-01");
		SaleKeHuGuanXi2 yan=new SaleKeHuGuanXi2();
		for (SaleKeHuGuanXi2 y : service2.findAll()) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				yan=y;
			}
		}
		return new AjaxResult(yan);
	}
	
}
